<template>
    <el-card>
        <div class="title-bar">
            <div>
                <div></div>
                <span>编辑签约信息</span>
            </div>
        </div>
        <div class="message-bar">
            <span>居民信息</span>
            <el-form ref="ruleResidentRef" :rules="residentRules" label-width="80" :inline="true"
                :model="residentFormData" class="demo-form-inline" style="--el-font-size-base:13px;">
                <el-form-item label="姓名" prop="name">
                    <el-input :disabled="true" v-model="residentFormData.name">
                    </el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="IDnumber">
                    <el-input v-model="residentFormData.IDnumber">
                    </el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select clearable v-model="residentFormData.gender">
                        <el-option :value="1" label="男" />
                        <el-option :value="0" label="女" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出生年月" prop="birthday">
                    <el-date-picker v-model="residentFormData.birthday" type="date" placeholder="请选择日期"
                        style="width: 200px;height: 40px;" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input placeholder="请输入" v-model="residentFormData.phone">
                    </el-input>
                </el-form-item>
                <el-form-item label="现居地">
                    <el-input placeholder="请输入" style="width: 300px;" v-model="residentFormData.address">
                    </el-input>
                </el-form-item>
                <el-form-item label="居民标签">
                    <el-select clearable v-model="residentFormData.tags">
                        <el-option value="" label="请选择" />
                        <el-option v-for="item in tagData" :label="item.name" :key="item._id"
                            :value="item._id"></el-option>
                    </el-select>
                </el-form-item>
                <div style="width: 100%;height: auto;display: flex;">
                    <div
                        style="height: 40px;width: 80px;font-size: 13px;color: #999;margin-right: 10px;padding-right: 12px;text-align: right;line-height: 40px;box-sizing: border-box;">
                        家庭成员</div>
                    <div class="relation-bar"
                        style="display: grid;grid-template-columns: repeat(5,200px);justify-content: space-between;width: auto;row-gap: 20px;column-gap: 25px;">
                        <div class="relation-box" v-for="item in relationData">
                            <img :src="item.otherId.avatar" alt="">
                            <section class="relation-message" style="height: auto;width:126px;">
                                <div style="height: 18px;display: flex;width: 133px;">
                                    <p style="line-height: 16px;" class="nameBar">{{
                                        item.otherId.name }}</p>
                                    <span style="margin: 0 20px 0 0;line-height: 12px;"> 26岁 </span>
                                    <img style="width: 12px;height: 12px;" src="/src/assets/girls.png" alt=""
                                        v-if="!item.otherId.gender">
                                    <img src="/src/assets/boys.png" alt="" v-else>
                                </div>
                                <span>{{ '关系：' + item.relationship }}</span>
                            </section>
                        </div>
                        <div class="addPart" style="color: #2984F8;cursor: pointer;height: 84px;" @click="addRelation">
                            +关联家庭成员</div>
                    </div>
                    <div></div>
                </div>
            </el-form>
            <div class="button-bar">
                <el-button type="primary" @click="toUpdateResident(ruleResidentRef)">保存</el-button>
            </div>

        </div>
        <div class="message-bar">
            <span>签约信息</span>
            <el-form ref="ruleSignRef" :rules="signRules" label-width="auto" :inline="true" :model="formData"
                class="demo-form-inline" style="--el-font-size-base:13px;">
                <el-form-item label="签约编号">
                    <div>{{ formData._id ? formData._id : '暂无' }}</div>
                </el-form-item>
                <el-form-item label="签约状态">
                    <div v-if="signData.state == 1" style="color:#3DD4A7">待审核</div>
                    <div v-if="signData.state == 2" style="color:#FDDB78">审核通过，等待用户支付</div>
                    <div v-if="signData.state == 0" style="color:#FA746B">已驳回，等待居民修改</div>
                    <div v-if="signData.state == 1" style="color:#3DD4A7">待审核</div>
                    <div v-else></div>
                </el-form-item>
                <el-form-item label="签约机构" prop="organizationId">
                    <el-select clearable v-model="formData.organizationId">
                        <el-option :value="item._id" :label="item.name" v-for="item in organizationData"
                            :key="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="签约团队" prop="teamId">
                    <el-select clearable v-model="formData.teamId" :disabled="!formData.organizationId">
                        <el-option :value="item._id" :label="item.name" v-for="item in teamData" :key="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="签约医生" prop="doctorId">
                    <el-select clearable v-model="formData.doctorId" :disabled="!formData.teamId">
                        <el-option :value="item._id" :label="item.name" v-for="item in doctorData" :key="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="服务包" prop="servicePackId">
                    <el-select clearable v-model="formData.servicePackId">
                        <el-option :value="item._id" :label="item.name" v-for="item in packData" :key="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="签约类型">
                    <div>{{ formData.type }}</div>
                </el-form-item>
                <el-form-item label="签约周期">
                    <div>{{ periodSign }}</div>
                </el-form-item>
                <el-form-item label="费用">
                    <div>{{ signPrice ? '￥' + signPrice : '' }}</div>
                </el-form-item>
                <el-form-item label="申请时间">
                    <div>{{ formData.applyTime }}</div>
                </el-form-item>
                <el-form-item label="生效日期" prop="effectiveDate">
                    <el-date-picker v-model="formData.effectiveDate" type="date" placeholder="请选择日期"
                        style="width: 200px;height: 40px;" />
                </el-form-item>
                <el-form-item label="签约备注" style="height: 120px;display: flex;">
                    <el-input v-model="formData.remark" style="width: 582px;height: 110px;" :rows="5" type="textarea"
                        placeholder="请输入签约备注" />
                </el-form-item>
            </el-form>
        </div>

        <div class="button-bar">
            <el-button type="primary" @click="toUpdate(ruleSignRef)">保存</el-button>
            <el-button @click="$router.back">返回</el-button>
        </div>
    </el-card>

    <AddRelation ref="relationRef" @getRelation="getRelation"></AddRelation>
</template>

<script setup>
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue';
import AddRelation from '../../resident/AddRelation.vue';
import { useRoute, useRouter } from 'vue-router';
import { addSignApi, getSignDetailApi, getSignFullApi, updateSignApi } from '../../../api/sighPending';
import { findOrganizationsApi } from '../../../api/organization';
import { searchTeamsApi } from '../../../api/teamManage';
import { searchDoctorsApi } from '../../../api/doctors';
import { findPackApi, getPackApi } from '../../../api/servicePack';
import { ElMessage } from 'element-plus';
import { findTagsApi } from '../../../api/tags'
import { findResidentRelationApi, getREsidentDetailApi, upDateREsidentApi } from '../../../api/resident';
const router = useRouter()
const route = useRoute()
// 签约周期
const periodSign = ref('')
// 费用
const signPrice = ref('')

const age = computed(() => {
    return getFullYear()
})
const relationRef = useTemplateRef('relationRef')
// 添加关系
function addRelation() {
    relationRef.value?.addRelationship(residentFormData.value._id)
    getRelation()
}

const formData = ref({

    residentId: '',
    organizationId: '',
    teamId: '',
    doctorId: '',
    servicePackId: '',
    type: '首次签约',
    remark: '',
    applyTime: '',
    effectiveDate: '',
    state: ''
})

watch(() => formData.value.servicePackId, () => {
    getPack()
})

const currentTime = new Date();

//获取当前签约时间
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

const residentFormData = ref({
    _id: '',
    name: '',
    IDnumber: '',
    gender: '',
    birthday: '',
    phone: '',
    address: '',
    tags: []
})

// 机构
const organizationData = ref([])
function findOrganization() {
    findOrganizationsApi()
        .then(res => {
            if (res.code == 200) {
                organizationData.value = res.data.rows
            }
        })
}

// 标签数据
const tagData = ref([])

function findTag() {
    findTagsApi()
        .then(res => {
            if (res.code == 200) {
                tagData.value = res.data.rows
            }
        })
}

const relationData = ref([])

// 获取亲属关系
function getRelation() {
    findResidentRelationApi
        ({ ownId: residentFormData.value._id })
        .then(res => {
            if (res.code == 200) {
                relationData.value = res.data
            }
        })
}

watch(() => residentFormData.value._id, () => {
    getRelation()
})

// 获取居民详情
function getResident() {
    getREsidentDetailApi({ _id: route.params._id })
        .then(res => {
            if (res.code == 200) {
                residentFormData.value = res.data
            }
        })
}

// 团队
const teamData = ref([]);
function findTeam() {
    searchTeamsApi({ organizationId: formData.value.organizationId })
        .then(res => {
            if (res.code == 200) {
                teamData.value = res.data.rows
            }
        })
}

watch(() => formData.value.organizationId, () => {
    if (!formData.value.organizationId) {
        formData.value.teamId = ''
    }
    findTeam()
})

// 医生
const doctorData = ref([]);
function findDoctor() {
    searchDoctorsApi({ teamId: formData.value.teamId })
        .then(res => {
            if (res.code == 200) {
                doctorData.value = res.data.rows
            }
        })
}

watch(() => formData.value.teamId, () => {
    if (!formData.value.teamId) {
        formData.value.doctorId = ''
    }
    findDoctor()
})


// 添加签约
function addSign() {
    addSignApi({
        ...formData.value,

        residentId: residentFormData.value._id
    })
        .then(res => {
            router.back()
            if (res.code == 200) {
                ElMessage({
                    message: '签约信息添加成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(res.message)
            }
        })
}

// 修改签约
function update() {
    updateSignApi(formData.value)
        .then(res => {
            if (res.code == 200) {
                router.back()
                ElMessage({
                    message: '签约信息保存成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(res.message)
            }
        })
}
// 修改居民
function updateResident() {
    upDateREsidentApi(residentFormData.value)
        .then(res => {
            if (res.code == 200) {

                ElMessage({
                    message: '居民信息保存成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(res.message)
            }
        })
}

// 服务包
const packData = ref([])
function findPack() {
    findPackApi()
        .then(res => {
            if (res.code == 200) {
                packData.value = res.data.rows
            }
        })
}



const signData = ref({})

// 获取签约详情
function getSignDetail() {
    getSignDetailApi({ _id: route.params._id })
        .then(res => {
            if (res.code == 200) {
                formData.value = res.data
                residentFormData.value = {
                    ...res.data.residentId,
                    tagIds: [res.data.residentId?.tags]
                }
            } else {
                formData.value.applyTime = formatDate(new Date())
            }
        })
}

// 获取服务包详情
function getPack() {
    getPackApi({ _id: formData.value.servicePackId })
        .then(res => {
            if (res.code == 200) {
                periodSign.value = res.data.period;
                signPrice.value = res.data.price
            }
        })
}

onMounted(() => {

    getResident()
    findOrganization()
    findTeam()
    findDoctor()
    findPack()
    getSignDetail()
    findTag()
    getRelation()
})

// 表单验证
const residentRules = ref({
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },

    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'blur',
        },
    ],
    name: [
        {
            required: true,
            message: '姓名不能为空',
            trigger: 'blur',
        },
    ],
    birthday: [
        {
            required: true,
            message: '生日不能为空',
            trigger: 'blur',
        },
    ],
    IDnumber: [
        {
            required: true,
            message: '身份证号不能为空',
            trigger: 'blur',
        },
    ],
    gender: [
        {
            required: true,
            message: '性别不能为空',
            trigger: 'blur',
        },
    ],

})

const signRules = ref({
    organizationId: [
        {
            required: true,
            message: '机构不能为空',
            trigger: 'blur',
        },
    ],
    teamId: [
        {
            required: true,
            message: '团队不能为空',
            trigger: 'blur',
        },
    ],
    doctorId: [
        {
            required: true,
            message: '签约医生不能为空',
            trigger: 'blur',
        },
    ],
    effectiveDate: [
        {
            required: true,
            message: '生效日期不能为空',
            trigger: 'blur',
        },
    ],
    servicePackId: [
        {
            required: true,
            message: '服务包不能为空',
            trigger: 'blur',
        },
    ],
})

// 修改签约
const toUpdate = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            if (!formData.value._id) {
                addSign()
            } else {
                update()
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 修改居民
const toUpdateResident = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            updateResident()


            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}


const ruleSignRef = ref()
const ruleResidentRef = ref()

</script>

<style scoped>
.title-bar {
    height: 40px;
    border-bottom: 1px solid #dbdbdb;

}

.title-bar>view {
    height: 20px;
    display: flex;
    align-items: center;
}

.title-bar>view>view {
    height: 20px;
    background-color: var(--el-color-primary);
    width: 6px;
    border-radius: 16px;
    margin-right: 15px;
}

.title-bar span {
    color: var(--el-title-font-color);
    font-size: var(--el-title-font-size);
    font-weight: var(--el-title-font-weight);
}

.message-bar span {
    display: inline-block;
    font-size: 16px;
    color: #333;
    margin-bottom: 20px;
}

.message-bar {
    border-bottom: 1px solid #dbdbdb;
    margin-top: 20px;
}

.el-form-item div {
    height: 40px;
    width: 200px;
    line-height: 40px;
    font-size: 13px;
    color: #333;
}

.el-input,
.el-select {
    width: 200px;
    height: 40px;
}

.el-form-item {
    margin-right: 100px;
    margin-bottom: 15px;
}

.button-bar {
    height: 40px;
    display: flex;
    justify-content: flex-start;
    margin-top: 20px;
    margin-bottom: 20px;
}

.relation-bar {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(5, 200px);
    justify-content: space-between;
    padding-right: 20px;

}

.relation-box {
    width: 200px;
    min-height: 84px;
    border-radius: 8px;
    border: 1px solid rgba(242, 242, 242, 1);
    display: flex;
    padding-top: 25px;
    padding-left: 20px;
    margin-bottom: 20px;
    box-sizing: border-box;
}

.relation-box>img {
    width: 40px;
    height: 40px;
    margin-right: 10px;
    border-radius: 50%;
}

.relation-bar .relation-box .relation-message {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}

.relation-message>div {
    display: inline-block;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.relation-message>div>p {
    font-size: 16px;
    color: #333;
    margin: 0;
    margin-right: 6px;
    line-height: 16px;
}

.relation-message>div>span,
.relation-message span {
    font-size: 12px;
    color: #999;
    margin-right: 20px;
    line-height: 12px;
}

.relation-message>div>img {
    width: 15px;
    height: 15px;
}

.addPart {
    width: 200px;
    height: 40px;
    line-height: 40px;
    font-size: 13px;
    font-weight: 400;
    display: flex;
    align-items: center;


}

.nameBar {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 隐藏超出部分 */
    text-overflow: ellipsis;
    /* 超出部分显示为省略号 */
    width: 50px;
}
</style>